<?php
/**
 * 公司
 */

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Model\BackendGroupModel;
use App\Model\BackendUserModel;
use App\Model\GroupApplyModel;

class GroupController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('auth');
    }

    /** 公司编辑 */
    public function edit()
    {
        $this->data['title'] = '公司编辑';
        $this->showSidebar();
        return view('backend.group.edit', $this->data);
    }

    /** 公司成员 */
    public function members()
    {
        $this->data['title'] = '公司成员';
        $this->showSidebar();
        return view('backend.group.members', $this->data);
    }

    /** 申请列表 */
    public function apply()
    {
        $this->showSidebar();
        $this->data['title'] = '申请加入公司';
        return view('backend.group.apply', $this->data);
    }

    /** 申请列表 */
    public function examine()
    {
        $this->showSidebar();
        $this->data['title'] = '申请加入公司';
        return view('backend.group.examine', $this->data);
    }

    /** 获取群组信息 */
    public function getGroupPost()
    {
        $group = BackendGroupModel::where('id', Auth::user()->backend_group_id)->select('id', 'group_name', 'description')->first();
        if ($group) {
            return $this->responseSuccess('成功', $group->toArray());
        } else {
            return $this->responseError('企业不存在');
        }
    }

    /** 設置公司 */
    public function setGroupPost()
    {
        $backendUser = Auth::user();
        if ($backendUser->backend_group_id) {
            if ($backendUser->backend_group_id != self::$params['group_id']) {
                return $this->responseError('修改错误企业信息');
            }

            $backendGroup = BackendGroupModel::where('id', self::$params['group_id'])->first();
            if ($backendGroup->group_name != self::$params['group_name'] && BackendGroupModel::checkNameValid(self::$params['group_name'])) {
                return $this->responseError('公司名称已经存在');
            }

            $res = BackendGroupModel::where('id', self::$params['group_id'])->update(['group_name' => self::$params['group_name'], 'description' => self::$params['description']]);
        } else {
            if (BackendGroupModel::checkNameValid(self::$params['group_name'])) {
                return $this->responseError('公司名称已经存在');
            }

            DB::beginTransaction();
            $backendGroupRes = BackendGroupModel::insert([
                'group_name' => self::$params['group_name'],
                'description' => self::$params['description'],
                'member_number' => 1,
                'admin_id' => $backendUser->id,
                'create_time' => time()
            ]);
            $backendGroupId = DB::getPdo()->lastInsertId();
            $res = BackendUserModel::where('id', $backendUser->id)->update(['backend_group_id' => $backendGroupId, 'is_group_admin' => 1]);
            if ($res && $backendGroupRes) {
                DB::commit();
                self::$params['group_id'] = $backendGroupId;
            } else {
                DB::rollBack();
                $res = false;
            }
        }

        if ($res) {
            return $this->responseSuccess('编辑成功', ['group_name' => self::$params['group_name'], 'group_id' => self::$params['group_id']]);
        } else {
            return $this->responseError('编辑失败');
        }
    }

    /** 列表群组成员 */
    public function listMembersPost()
    {
        $backendUser = Auth::user();
        if ($backendUser->backend_group_id == 0) {
            $total = 0;
            $list = [];
        } else {
            $where = ['backend_group_id' => $backendUser->backend_group_id];
            if (isset(self::$params['keyword']) && !empty(self::$params['keyword'])) {
                $where[] = ['nickname', 'like', '%' . self::$params['keyword'] . '%'];
            }

            $offset = (self::$params['page_num'] - 1) * self::$params['page_size'];
            $total = BackendUserModel::where($where)->count();
            $list = BackendUserModel::where($where)->offset($offset)->limit(self::$params['page_size'])->get()->toArray();
        }

        return $this->responseSuccess('成功', ['total' => $total, 'list' => $list]);
    }

    /** 列表企业 */
    public function listGroupPost()
    {
        $backendUser = Auth::user();
        if ($backendUser->backend_group_id > 0) {
            $total = 0;
            $list = [];
        } else {
            $where = [];
            if (isset(self::$params['keyword']) && !empty(self::$params['keyword'])) {
                $where[] = ['backend_group.group_name', 'like', '%' . self::$params['keyword'] . '%'];
            }

            $offset = (self::$params['page_num'] - 1) * self::$params['page_size'];
            $user_id = $backendUser->id;
            $total = BackendGroupModel::join('group_apply', function ($join) use ($user_id) {
                $join->on('group_apply.group_id', '=', 'backend_group.id')->where('group_apply.user_id', '=', $user_id);
            }, null, null, 'left')->where($where)->count();
            $list = BackendGroupModel::join('group_apply', function ($join) use ($user_id) {
                $join->on('group_apply.group_id', '=', 'backend_group.id')->where('group_apply.user_id', '=', $user_id);
            }, null, null, 'left')
                ->select('backend_group.*', 'group_apply.status')
                ->where($where)->offset($offset)->limit(self::$params['page_size'])->get()->toArray();
        }

        return $this->responseSuccess('成功', ['total' => $total, 'list' => $list]);
    }

    /** 添加申请加入企业 */
    public function addApply()
    {
        $backendUser = Auth::user();
        if ($backendUser->backend_group_id) {
            return $this->responseError('你已经是企业成员');
        }

        $backendGroup = BackendGroupModel::where('id', self::$params['apply_group_id'])->first();
        if (empty($backendGroup)) {
            return $this->responseError('申请加入的企业不存在');
        }

        $groupApply = GroupApplyModel::where(['group_id' => self::$params['apply_group_id'], 'status' => 1, 'user_id' => $backendUser->id])->first();
        if ($groupApply) {
            return $this->responseError('您已申请加入此企业，请耐心等待审核');
        }

        $data = [
            'user_id' => $backendUser->id,
            'group_id' => $backendGroup->id,
            'status' => 1,
            'apply_reason' => self::$params['apply_reason'],
            'createtime' => time()
        ];
        $res = GroupApplyModel::insert($data);
        if ($res) {
            return $this->responseSuccess('申请加入企业成功');
        } else {
            return $this->responseError('申请加入企业失败');
        }
    }

    public function delapply()
    {
        $backendUser = Auth::user();
        $backendGroup = BackendGroupModel::where('id', self::$params['apply_group_id'])->first();
        if (empty($backendGroup)) {
            return $this->responseError('申请加入的企业不存在');
        }

        $groupApply = GroupApplyModel::where(['group_id' => self::$params['apply_group_id'], 'status' => 1, 'user_id' => $backendUser->id])->first();
        if (empty($groupApply)) {
            return $this->responseError('您没有申请加入过此企业');
        }

        $data = ['status' => 2, 'examine_time' => time()];
        $res = GroupApplyModel::where('id', $groupApply->id)->update($data);
        if ($res) {
            return $this->responseSuccess('申请加入企业成功');
        } else {
            return $this->responseError('申请加入企业失败');
        }
    }

    /** 列表申请列表 */
    public function listApply()
    {
        $backendUser = Auth::user();
        if ($backendUser->backend_group_id == 0 || $backendUser->is_group_admin != 1) {
            $total = 0;
            $list = [];
        } else {
            $where = [];
            if (isset(self::$params['keyword']) && !empty(self::$params['keyword'])) {
                $where[] = ['backend_user.nickname', 'like', '%' . self::$params['keyword'] . '%'];
            }

            if (isset(self::$params['status']) && self::$params['status'] != -1) {
                $where[] = ['group_apply.status', '=', self::$params['status']];
            }

            $offset = (self::$params['page_num'] - 1) * self::$params['page_size'];
            $backend_group_id = $backendUser->backend_group_id;

            $total = GroupApplyModel::join('backend_user', function ($join) use ($backend_group_id) {
                $join->on('backend_user.id', '=', 'group_apply.user_id')->where('group_apply.group_id', '=', $backend_group_id);
            })->where($where)->count();
            $list = GroupApplyModel::join('backend_user', function ($join) use ($backend_group_id) {
                $join->on('backend_user.id', '=', 'group_apply.user_id')->where('group_apply.group_id', '=', $backend_group_id);
            })->select('group_apply.*', 'backend_user.nickname', 'backend_user.headimgurl')
                ->where($where)
                ->offset($offset)
                ->limit(self::$params['page_size'])
                ->get()
                ->toArray();
        }

        return $this->responseSuccess('成功', ['total' => $total, 'list' => $list]);
    }

    public function examineApply()
    {
        $backendUser = Auth::user();
        if ($backendUser->backend_group_id == 0 || $backendUser->is_group_admin != 1) {
            return $this->responseError('操作失败');
        } else {
            $groupApply = GroupApplyModel::where('id', self::$params['apply_id'])->first();
            if (empty($groupApply)) {
                return $this->responseError('申请不存在');
            }

            if ($groupApply['status'] != 1 || $groupApply['user_id'] == $backendUser->id || $groupApply['group_id'] != $backendUser['backend_group_id']) {
                return $this->responseError('操作的申请非法');
            }

            if (self::$params['operate'] == 1) {
                DB::beginTransaction();
                $res1 = GroupApplyModel::where('id', $groupApply->id)->update(['status' => 3, 'examine_time' => time()]);
                $res2 = BackendUserModel::where('id', $groupApply->user_id)->update(['backend_group_id' => $groupApply->group_id]);
                $res3 = BackendGroupModel::where('id', $groupApply->group_id)->increment('member_number', 1);
                if ($res1 && $res2 && $res3) {
                    DB::commit();
                } else {
                    DB::rollBack();
                }
            } else {
                GroupApplyModel::where('id', $groupApply->id)->update(['status' => 4, 'examine_time' => time()]);
            }

            return $this->responseSuccess('操作成功');
        }
    }
}
